package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BaseException;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.sun.mail.imap.protocol.ID;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForList(qo);
        for (CarPackageAudit audit:carPackageAudits) {
            //进行单表查询,程序中遍历的时候,再去查询用户的信息(基本不变,可以放入缓存中),
            //关联查询用户的名称,audit.setCreator()==>获取到数据库储存当前创建人ID
            //在遍历过程中,调用userService,根据ID 获取到用户对象,然后可以获取到用户的名称,设置到creator中,
            //前台展示的,看到的是用户的名称
            audit.setCreator(userService.get(Long.parseLong(audit.getCreator())).getUserName());
            if (audit.getAuditorId() !=null) {
                audit.setAuditorName(userService.get(audit.getAuditorId()).getUserName());
            }
        }
        return new TablePageInfo<CarPackageAudit>(carPackageAudits);
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.insert(carPackageAudit);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(Long id) {
            carPackageAuditMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public InputStream getProcessImg(Long id) {
        InputStream inputStream = null;
        //根据ID查询CarPackageAudit对象
        CarPackageAudit audit = this.get(id);
        Long bpmninfoId = audit.getBpmninfoId();
        //查询bpmninfoId 对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmninfoId);
        //可以通过bpmnInfo获取流程定义的ID
        //判断流程是否正在进行中,如果正在进行中,需要高亮节点,如果已经结束,只需看流程图,不需要高亮节点
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        List<String> highLightedActivities = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            //流程正在流转,查找当前节点,高亮当前节点
            highLightedActivities = runtimeService.getActiveActivityIds(audit.getInstanceId());
        }else {
            //流程已经结束,不需要高亮节点
            highLightedActivities = Collections.EMPTY_LIST;
        }

        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();    //生成图片的处理类
        //generateDiagram(bpmn模型,需要高亮节点ID集合,,需要高亮节点ID集合)
        inputStream = generator.generateDiagram(bpmnModel,
                highLightedActivities,
                Collections.EMPTY_LIST,
                "宋体",
                "宋体",
                "宋体"
        );
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        //合理性校验
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("非法操作");
        }
        //更新CarPackageAudit对象状态
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
        //审核撤销时,需要把当前审核人字段设置为空
        carPackageAuditMapper.setAuditor(id,null);
        //更新ServiceItem状态
        serviceItemService.changeStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程撤销");
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //进行合理化校验
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            //处于审核中的记录才能进行审核
            throw new BusinessException("非法操作");
        }
        //获取流程实例目前的任务
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId())       //根据流程实例ID查询活动节点
                .singleResult();
        //完成任务设置流程变量
        Map<String,Object> variables = new HashMap<>();
        variables.put("auditStatus",auditStatus);
        taskService.complete(currentTask.getId(),variables);
        //判断同意还是拒绝
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            //同意
            //判断是否有下一个节点
            Task nextTask = taskService.createTaskQuery()
                    .processInstanceId(audit.getInstanceId())       //根据流程实例ID查询活动节点
                    .singleResult();
            if (nextTask==null) {
                //流程结束了
                audit.setStatus(CarPackageAudit.STATUS_PASS);       //状态修改为同意
                audit.setAuditorId(null);       //设置当前审核人为空
                //修改ServiceItem的状态
                serviceItemService.changeStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }else {
                //流程还没有结束
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee())); //设置审核对象中当前审核人ID设置下一个节点处理人
            }
        }else {
            //拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);         //状态修改为拒绝
            audit.setAuditorId(null);       //设置当前审核人为空
            //修改ServiceItem的状态
            serviceItemService.changeStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }
        audit.setAuditTime(new Date());
        User currentUser = ShiroUtils.getUser();
        audit.setAuditUserIds(audit.getAuditUserIds() + "[" + currentUser.getId() + "]");
        String infoStr = CarPackageAudit.STATUS_PASS.equals(auditStatus) ? "同意" : "拒绝";
        audit.setInfo(audit.getInfo() + "<br>" + currentUser.getUserName() + infoStr + ",批注:" + info);
        this.updateFromAudit(audit);
    }

    private void updateFromAudit(CarPackageAudit audit) {
        carPackageAuditMapper.updateFromAudit(audit);
    }
}

